package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //本质查询订单表的总金额，前提是已经完成的订单
        //将每个订单的金额和日期存储到集合中
        //select da from orders where complete_time between begin and end
        //datalist、turnoverList
        //最后封装VO返回
        //前端要的是begin到end之间每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        //从begin加到end
        dateList.add(begin);
        while (!begin.equals(end)) {
            //计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //先自增放入集合，然后判断，所以end不用添加
        //查询时间范围内每一天的营业额数据
        //select sum(amount) from orders where order_time between beginTime and end endTime and status = 5(已完成的订单)
        // 400,500,90,250,361

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1.补全日期集合dateList
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //2.获取totalUserList
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        // SELECT count(*) FROM USER WHERE create_time < #{end}
        for (LocalDate date : dateList) {
            //3.获取newUserList
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            Integer total = userMapper.getTotalUserStatistics(map);
            totalUserList.add(total);

            map.put("begin", beginTime);
            Integer newUserTotal = userMapper.getNewUserStatistics(map);
            newUserList.add(newUserTotal);

        }

        //4.封装UserReportVO
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 统计指定时间内的订单量
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //1.获取dateList
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //遍历dateList
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //获取每日订单数orderCountList ；select count(id) from orders where order_time between begin and end
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //获取每日有效订单数validOrderCountList select count(id) from orders where status = 5 and order_time between begin and end
            Integer valiOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(valiOrderCount);
        }
        //获取订单总数、有效订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompleteRate = 0.0;
        if (totalOrderCount > 0 && validOrderCount > 0) {
            orderCompleteRate = (double) validOrderCount / (double) totalOrderCount;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList))
                .orderCountList(StringUtils.join(orderCountList))
                .validOrderCountList(StringUtils.join(validOrderCountList))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompleteRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

        //遍历dateList

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10List = orderMapper.getSalesTop10(beginTime,endTime);
        /*方法一：for循环遍历处理

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : salesTop10List) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }
         */
        //方法二：stream流处理
        List<String> names = salesTop10List.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        List<Integer> numbers = salesTop10List.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {

        //查询数据库，获取营业数据最近30天
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //获取概览数据：
        // 营业额、订单完成率、新增用户数、有效订单、平均客单价
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
        //通过POI将数据写入Excel文件中

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //填充总览数据
            excel.getSheetAt(0).getRow(1).getCell(1).setCellValue("统计时间："+ begin + " 至 " + end);
            excel.getSheetAt(0).getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            excel.getSheetAt(0).getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            excel.getSheetAt(0).getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            excel.getSheetAt(0).getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            excel.getSheetAt(0).getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            List<LocalDate> dateList = new ArrayList<>();
            dateList.add(begin);
            while (!begin.equals(end)) {
                begin = begin.plusDays(1);
                dateList.add(begin);
            }
            Integer line = 7;
            for (LocalDate date : dateList) {
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                excel.getSheetAt(0).getRow(line).getCell(1).setCellValue(String.valueOf(date));
                excel.getSheetAt(0).getRow(line).getCell(2).setCellValue(data.getTurnover());
                excel.getSheetAt(0).getRow(line).getCell(3).setCellValue(data.getValidOrderCount());
                excel.getSheetAt(0).getRow(line).getCell(4).setCellValue(data.getOrderCompletionRate());
                if(data.getTurnover() == 0){
                    excel.getSheetAt(0).getRow(line).getCell(5).setCellValue(0.00);
                }else{
                    excel.getSheetAt(0).getRow(line).getCell(5).setCellValue(businessData.getUnitPrice());
                }
                excel.getSheetAt(0).getRow(line).getCell(6).setCellValue(businessData.getNewUsers());
                line++;
            }


            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }




    }

    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", status);
        Integer result = orderMapper.countByMap(map);
        return result;
    }


}
